package net.guerlab.smart.platform.user.service.entity;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import net.guerlab.smart.platform.user.core.domain.OperationLogDTO;
import net.guerlab.spring.commons.dto.DefaultConvertDTO;
import net.guerlab.spring.commons.util.SpringApplicationContextUtil;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;

/**
 * 操作记录
 *
 * @author guer
 */
@Data
@Table(name = "user_operation_log")
public class OperationLog implements DefaultConvertDTO<OperationLogDTO> {

    /**
     * 操作记录ID
     */
    @Id
    private Long operationLogId;

    /**
     * 应用名称
     */
    @Column(name = "applicationName", nullable = false, updatable = false)
    private String applicationName;

    /**
     * 操作时间
     */
    @Column(name = "operationTime", nullable = false, updatable = false)
    private LocalDateTime operationTime;

    /**
     * 操作内容
     */
    @Column(name = "operationContent", nullable = false, updatable = false)
    private String operationContent;

    /**
     * 操作参数
     */
    @Column(name = "operationParams", nullable = false, updatable = false)
    private String operationParams;

    /**
     * 用户ID
     */
    @Column(name = "userId", nullable = false, updatable = false)
    private Long userId;

    /**
     * 用户名
     */
    @Column(name = "username", nullable = false)
    private String username;

    /**
     * 姓名
     */
    @Column(name = "name", nullable = false)
    private String name;

    public OperationLog setOperationParamsObject(Object obj) {
        try {
            operationParams = SpringApplicationContextUtil.getContext().getBean(ObjectMapper.class)
                    .writeValueAsString(obj);
        } catch (Exception e) {
            operationParams = obj.toString();
        }

        return this;
    }
}
